package com.one.consumer.reserve.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.one.common.config.CMemoryData;
import com.one.common.config.RouterPath;
import com.one.common.manager.RouterManager;
import com.one.common.manager.imageloader.LoaderManager;
import com.one.common.model.bean.BannerBean;
import com.one.common.model.bean.UserInfoBean;
import com.one.common.utils.ClickUtils;
import com.one.common.utils.Logger;
import com.one.common.utils.StringUtils;
import com.one.common.view.widget.InputLayout;
import com.one.common.view.widget.MyTitleBar;
import com.one.consumer.BaseActivityC;
import com.one.consumer.R;
import com.one.consumer.common.extra.LocationExtra;
import com.one.consumer.reserve.model.bean.DEStyleBean;
import com.one.common.common.order.extra.CustomExtra;
import com.one.common.common.order.extra.ReserveExtra;
import com.one.consumer.reserve.model.bean.YouhuijuanResaultBean;
import com.one.consumer.reserve.model.bean.YouhuiquanBean;
import com.one.consumer.reserve.presenter.AddReserveDePresenter;
import com.one.consumer.reserve.ui.view.AddReserveView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.NumberFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

import static com.one.common.model.http.NetConstant.IMG_HOST;

/**
 * author ：zhulunjun
 * email  ：zhulunjun@qq.com
 * date   ：2018/10/21 下午7:49
 * description ：装修预约资料编辑页
 **/
@Route(path = RouterPath.ADD_RESERVE_DE)
public class AddReserveDEActivity extends BaseActivityC<AddReserveDePresenter> implements AddReserveView {
    @BindView(R.id.banner)
    ConvenientBanner banner;
    @BindView(R.id.il_type)
    InputLayout ilType;
    @BindView(R.id.il_city)
    InputLayout ilCity;
    @BindView(R.id.il_area)
    InputLayout ilArea;
    @BindView(R.id.il_contact)
    InputLayout ilContact;
    @BindView(R.id.il_phone)
    InputLayout ilPhone;
    @BindView(R.id.il_address)
    InputLayout ilAddress;
    @BindView(R.id.il_money)
    InputLayout ilMoney;
    @BindView(R.id.iv_icon)
    ImageView ivIcon;
    @BindView(R.id.il_project_name)
    InputLayout ilProjectName;
    @BindView(R.id.il_type_name)
    InputLayout ilTypeName;
    @BindView(R.id.il_program_name)
    InputLayout ilProgramName;
    @BindView(R.id.il_price)
    InputLayout ilPrice;
    @BindView(R.id.tv_btn)
    TextView tvBtn;
    @BindView(R.id.ll_submit)
    LinearLayout llSubmit;

    private OptionsPickerView pickerView;
    private ArrayList<DEStyleBean> optionsItems = new ArrayList<>();
    private String styleId;
    private DEStyleBean mStyle;
    private ReserveExtra mExtra;

    @Override
    protected void initPresenter() {
        mPresenter = new AddReserveDePresenter(this, this);
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_add_reserve_de;
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        mExtra = (ReserveExtra) getIntent().getSerializableExtra(ReserveExtra.getExtraName());
        String title;
        if (mExtra.getType().equals(ReserveExtra.STYLE_DE)) {
            title = "装修预约";
        } else if (mExtra.getType().equals(ReserveExtra.STYLE_DY)) {
            title = "设计预约";
        } else {
            title = "定制加配";
        }
        getMyTitleBar().setMode(MyTitleBar.Mode.BACK_TITLE)
                .setTitleText(title);
    }

    @Override
    public void initView() {
        super.initView();
        pickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                ilType.getTvCenter().setText(optionsItems.get(options1).getStyle_name());
                styleId = optionsItems.get(options1).getStyle_id() + "";
                mStyle = optionsItems.get(options1);
            }
        }).setTitleSize(18)
                .build();

        pickerView.setPicker(optionsItems);

        ilType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 选择类型
                pickerView.show();
            }
        });

        ilCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 选择地址
                RouterManager.getInstance().goForResult(AddReserveDEActivity.this, RouterPath.SELECT_LOCATION);
            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        setMoneyView();
        customInto();
        mPresenter.getBanner();
        mPresenter.getStyles();
    }

    /**
     * 显示报价,设置报价显示
     */
    private void setMoneyView() {
        if (mExtra.getType().equals(ReserveExtra.STYLE_DY)) {
            ilMoney.setVisibility(View.VISIBLE);
            ivIcon.setImageResource(R.mipmap.ic_dy);
            ilArea.getEditView().addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (mStyle != null && StringUtils.getDoubleToString(charSequence.toString()) > 0) {
                        double price = StringUtils.getDoubleToString(mStyle.getStyle_price());
                        double area = StringUtils.getDoubleToString(charSequence.toString());
//                        ilMoney.getTvCenter().setText((price * area ) + "");
                        loadYouhuijuanDatas((price*area)+"",mExtra.getType());
                    }
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if(TextUtils.isEmpty(editable.toString())){
                        ilMoney.setText("0");
                    }
                }
            });
        }
    }

    /**
     * 定制加配显示
     */
    private void customInto() {
        if (mExtra.getType().equals(ReserveExtra.STYLE_PR)) {
            ilArea.setVisibility(View.GONE);
            ilType.setVisibility(View.GONE);
            ivIcon.setImageResource(R.mipmap.ic_cu);
            tvBtn.setText("立即加配");
            ilProjectName.setVisibility(View.VISIBLE);
            ilTypeName.setVisibility(View.VISIBLE);
            ilProgramName.setVisibility(View.VISIBLE);
            ilPrice.setVisibility(View.VISIBLE);
            CustomExtra customExtra = mExtra.getCustomExtra();
            ilProjectName.getTvCenter().setText(customExtra.getProjectName());
            ilTypeName.getTvCenter().setText(customExtra.getTypeName());
            ilProgramName.getTvCenter().setText(customExtra.getProgramName());
            ilPrice.getTvCenter().setText(customExtra.getPrice());
            loadYouhuijuanDatas(ilPrice.getText().toString(),"5");
        }
    }

    /**
     * 获取优惠
     */
    private void loadYouhuijuanDatas(String ilMoneyStr,String tye){
        RequestParams params = new RequestParams("https://yinlong.yinweish.com/kmCouponController/v1.0/findMyCoupons_");
        UserInfoBean bean = CMemoryData.getUserInfo();
        params.addBodyParameter("member_account",bean.getMember_account());
        params.addBodyParameter("fee", ilMoneyStr+"");
        params.addBodyParameter("use_scene", tye);
        params.setCacheMaxAge(0);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String data = jsonObject.optString("data");

                    NumberFormat nf = NumberFormat.getNumberInstance();
                    nf.setMaximumFractionDigits(2);

                    if (mExtra.getType().equals(ReserveExtra.STYLE_DY)) {//设计预约
                        if (TextUtils.isEmpty(data))
                            ilMoney.setText(ilMoneyStr);
                        YouhuiquanBean datas = new Gson().fromJson(data, YouhuiquanBean.class);
                        if (datas.getRule() == 1) {//满减卷
                            ilMoney.setText((Double.valueOf(ilMoneyStr) - datas.getMoney()) + "");
                        } else {//折扣卷
                            ilMoney.setText(nf.format(Double.valueOf(ilMoneyStr) * datas.getMoney()) + "");
                        }
                    }else if(mExtra.getType().equals(ReserveExtra.STYLE_PR)){//定制加配
                        if (TextUtils.isEmpty(data))
                            ilPrice.setText(ilMoneyStr);
                        YouhuiquanBean datas = new Gson().fromJson(data, YouhuiquanBean.class);
                        if (datas.getRule() == 1) {//满减卷
                            ilPrice.setText((Double.valueOf(ilMoneyStr) - datas.getMoney()) + "");
                        } else {//折扣卷
                            ilPrice.setText(nf.format(Double.valueOf(ilMoneyStr) * datas.getMoney()) + "");
                        }
                    }
                    // 更新价格
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(Callback.CancelledException cex) {}
            @Override
            public void onFinished() {}
        });
    }

    @Override
    public void setBanner(ArrayList<BannerBean> banners) {
        banner.setPages(
                new CBViewHolderCreator() {
                    @Override
                    public LocalImageHolderView createHolder(View itemView) {
                        return new LocalImageHolderView(itemView);
                    }

                    @Override
                    public int getLayoutId() {
                        return R.layout.layout_banner;
                    }
                }, banners)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        // TODO banner点击事件
                    }
                });
    }

    @Override
    public void setMainInfo(String res) {

    }

    @Override
    public void setStyle(ArrayList<DEStyleBean> deStyleBeans) {
        this.optionsItems.addAll(deStyleBeans);
    }


    public class LocalImageHolderView extends Holder<BannerBean> {

        ImageView imageView;

        public LocalImageHolderView(View itemView) {
            super(itemView);
        }

        @Override
        protected void initView(View itemView) {
            imageView = (ImageView) itemView;
        }

        @Override
        public void updateUI(BannerBean data) {

            LoaderManager.getLoader().loadNet(imageView, IMG_HOST + data.getBanner_img());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (banner != null && !banner.isTurning()) {
            banner.startTurning(2000);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (banner != null) {
            banner.stopTurning();
        }
    }


    /**
     * 提交预约
     */
    @OnClick(R.id.ll_submit)
    public void submit() {
        if(ClickUtils.isFastClick())return;
        if (mExtra.getType().equals(ReserveExtra.STYLE_PR)) {
            // 定制加配--改造
            mPresenter.order(ilContact.getText().toString(),
                    ilPhone.getText().toString(),
                    ilCity.getText().toString() + ilAddress.getText().toString(),
                    locationExtra,
                    mExtra.getCustomExtra());
        } else {
            // 装修\设计预约
            mPresenter.reserve(styleId, ilArea.getText().toString(),
                    ilContact.getText().toString(),
                    ilPhone.getText().toString(),
                    ilCity.getText().toString() + ilAddress.getText().toString(),
                    locationExtra);
        }
    }


    private LocationExtra locationExtra;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RouterManager.RESULT_REQUEST_CODE_DEFAULT && data != null) {
            // 地址
            locationExtra = (LocationExtra) data.getSerializableExtra(LocationExtra.getExtraName());
            Logger.d("地址" + requestCode);
            if (locationExtra != null) {
                ilCity.getTvCenter().setText(locationExtra.getTitle());
                Logger.d("地址" + locationExtra.toString());
            }
        }
    }
}
